package com.situ.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;

@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String uri = httpServletRequest.getRequestURI();
		// uri: /Java202007Web/course
		// uri: /Java202007Web/login.jsp
		// 你要去登录界面，但是要求你已经登录：将您重定向的次数过多。
		System.out.println("uri: " + uri);
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		// /Java202007Web/user?method=login
		String method = httpServletRequest.getParameter("method");
		
		if ("/login.jsp".equals(servletPath) 
				|| ("/user".equals(servletPath) && "login".equals(method))
				|| "/checkImg".equals(servletPath)
				|| servletPath.endsWith(".js") 
				|| servletPath.endsWith(".css")
				|| servletPath.endsWith(".css.map") 
				|| servletPath.endsWith(".png")
				|| servletPath.endsWith(".jpg")) {
			// // 这些路径是不需要验证登录，直接放行
			chain.doFilter(request, response);
		} else {
			// 需要验证是否登录的操作
			HttpSession session = httpServletRequest.getSession();
			User user = (User) session.getAttribute("user");
			if (user == null) {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
				return;
			}
			
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
